package com.logic.landseaserver.ws;

import java.text.DecimalFormat;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.logic.common.enums.HttpCodeEnum;
import com.logic.common.exception.BusinessException;
import com.logic.common.util.CommonResult;
import com.logic.common.util.CommonResultMap;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.enums.BTypeEnum;
import com.logic.landseaserver.common.enums.BillInputTypeEnum;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.domain.Contract;
import com.logic.landseaserver.domain.RealBill;
import com.logic.landseaserver.models.prepayment.service.AutoPayBillService;
import com.logic.landseaserver.persistence.read.ContractReadMapper;
import com.logic.landseaserver.persistence.read.RealBillReadMapper;
import com.logic.landseaserver.service.IRealBillService;
import com.logic.landseaserver.service.impl.SendMsgServiceImpl;
import com.logic.landseaserver.service.utils.ResetQueryUtil;
import com.logic.landseaserver.ws.dto.RealBillDTO;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 
 *
 * 项目名称：system-server</br>
 * 类名称：RealBillRest</br>
 * 类描述：实时账单</br>
 * 创建人：Aaron</br>
 * 创建时间：2017年7月28日 下午4:29:04</br>
 * @version 1.0
 *
 */
@Path("/realBill")
@Api(value="realBill")
public class RealBillRest 
{

    protected Logger logger = LoggerFactory.getLogger(RealBillRest.class);
    
    @Autowired
    private IRealBillService realBillServiceImpl;
    
    @Autowired
    private RealBillReadMapper realBillReadMapper;
    
    @Autowired
    private ContractReadMapper contractReadMapper;

    @Autowired
    private SendMsgServiceImpl sendMsgServiceImpl;
    
    @Autowired
    private AutoPayBillService autoPayBillService;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Create a new realBill")
    public Response create(@ApiParam(value = "param", required = true) RealBill realBill)
    {
        CommonResultMap map = new CommonResultMap();
        try
        {
            realBill.setInputType(BillInputTypeEnum.BACK.getCode());
            // 直接生成实时账单的编号
            // 获取合同编号
            Contract contract = contractReadMapper.selectByPrimaryKey(realBill.getContractId());
            if (null == contract)
            {
                throw new LandseaBusinessException(LandseaErrorMessageEnum.APPLY_CONTRACT_NOT_FOUND);
            }
            
            // 获取下一个流水
            Integer nextLastNumber = realBillReadMapper.getMaxRealBillNoCode(realBill.getContractId());
            String nextLastNumStr = new DecimalFormat("0000").format(nextLastNumber);
            // 规则：合同编号 + "RT" + 4位流水
            String nextBillNo = contract.getContractNo() + "RT" + nextLastNumStr;
            realBill.setBillNo(nextBillNo);
            
            int id = realBillServiceImpl.insert(realBill);
            //发送短信
            // 需要推送消息Tony(P4需要做的)
            if(id!=0){
                //获取实时账单ID
                sendMsgServiceImpl.sendMessage(contract.getId(), BTypeEnum._BT2.getCode(),id);
            }
            
            // 自动抵扣
            autoPayBillService.autoPayByUserRoom(contract.getUserId(), contract.getRoomId());
            
            map.setData(realBillServiceImpl.getDTO(id));
            map.setResult(CommonResult.SUCCESS, "Create success");
        }
        catch (BusinessException e)
        {
            logger.error("RealBillRest|create failed.", e);
            map.setResult(e);
        }
        catch (Exception e)
        {
            logger.error("RealBillRest|create failed.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


	@DELETE
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "logic delete realBill by set deleted")
    public Response logicDelete(@ApiParam(value = "param", required = true) @QueryParam("realBillId") String id) {
        CommonResultMap map = new CommonResultMap();
        try {
        	realBillServiceImpl.delete(id);
            map.setResult(CommonResult.SUCCESS,"delete realBill");
        } catch (BusinessException e) {
            logger.error("logicDelete error.", e);
            map.setResult(e);
        }  catch (Exception e) {
            logger.error("logicDelete error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }

	@PUT
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "edit realBill ")
    public Response update(@ApiParam(value = "param", required = true) RealBill realBill) {
        CommonResultMap map = new CommonResultMap();
        try {
        	realBillServiceImpl.update(realBill);
            map.setResult(CommonResult.SUCCESS,"edit realBill");
        } catch (BusinessException e) {
            logger.error("update error.", e);
            map.setResult(e);
        }  catch (Exception e) {
            logger.error("update error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


    @GET
    @Path("/detail/{realBillId}")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Get realBill by realBill id")
    public Response retrieveDTO(
            @ApiParam(value = "param", required = true) @PathParam("realBillId") Integer realBillId) {
        CommonResultMap map = new CommonResultMap();
        try {
            map.setData(realBillServiceImpl.getDTO(realBillId));
            map.setResult(CommonResult.SUCCESS);
        } catch (Exception e) {
            logger.error("retrieveDTO error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
    }


	@POST
	@Path("/detail/list")
	@Produces(MediaType.APPLICATION_JSON)
	@Consumes(MediaType.APPLICATION_JSON)
	@ApiOperation(value = "list realBills")
	public Response listDTO(@ApiParam(value = "param", required = true) QueryUtil queryUtil){
        CommonResultMap map = new CommonResultMap();
        List<RealBillDTO> realBillList = null;
        try {
            queryUtil.getPagingTool().calculateStartIndex();
            ResetQueryUtil.reset(queryUtil);
            realBillList = realBillServiceImpl.queryDTO(queryUtil);
            Integer totalCount = queryUtil.getPagingTool().getTotalNum();
            map.setData(realBillList);
            map.setResultTotalCount(totalCount);
            map.setResult(CommonResult.SUCCESS);

        } catch (Exception e) {
            logger.error("listDTO error.", e);
            map.setResult(CommonResult.ERROR, e.getMessage());
        }
        return Response.status(HttpCodeEnum.OK.getCode()).entity(map).build();
	}

}
